package org.ourgrid.worker.business.controller.patdown;

import org.ourgrid.common.executor.Executor;
import org.ourgrid.common.executor.ExecutorException;
import org.ourgrid.common.executor.ExecutorHandle;
import org.ourgrid.common.executor.ExecutorResult;
import org.ourgrid.common.interfaces.WorkerExecutionServiceClient;
import org.ourgrid.worker.WorkerConstants;
import org.ourgrid.worker.business.dao.EnvironmentDAO;
import org.ourgrid.worker.business.dao.ExecutionDAO;
import org.ourgrid.worker.business.dao.WorkerDAOFactory;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

public class WorkerExecutionInfo {

	private ExecutionDAO execDAO;
	private EnvironmentDAO envDAO;

	private static ServiceManager manager;

	/**
	 * @return the execDAO
	 */
	public ExecutionDAO getExecDAO() {
		return execDAO;
	}

	/**
	 * @param execDAO
	 *            the execDAO to set
	 */
	public void setExecDAO(ExecutionDAO execDAO) {
		this.execDAO = execDAO;
	}

	/**
	 * @return the envDAO
	 */
	public EnvironmentDAO getEnvDAO() {
		return envDAO;
	}

	/**
	 * @param envDAO
	 *            the envDAO to set
	 */
	public void setEnvDAO(EnvironmentDAO envDAO) {
		this.envDAO = envDAO;
	}

	public static void fetchExecution(ExecutorHandle handle) {

		Executor executor = WorkerDAOFactory.getInstance().getExecutorDAO().getExecutor();
		WorkerExecutionServiceClient executionClient = (WorkerExecutionServiceClient) manager.getObjectDeployment(
				WorkerConstants.WORKER_EXECUTION_CLIENT).getProxy();

		try {
			// patdown
			System.out.println("Executor's class: " + executor.getClass().getName());
			System.out.println("Execution Client's class: "+executionClient.getClass().getName());

			// -------
			ExecutorResult result = executor.getResult(handle);

			// patdown
			System.out.println("Execution finished");
			// -------
			executor.finishCommandExecution(handle);
			executionClient.executionResult( result );
		} catch (ExecutorException ee) {
			executionClient.executionError( ee );
		} catch (Exception e) {
			executionClient.executionError(new ExecutorException(e));
		}

	}

	/**
	 * @param manager the manager to set
	 */
	public static void setManager(ServiceManager manager) {
		WorkerExecutionInfo.manager = manager;
	}

}
